package com.ceicei.jingdong;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ceicei.project.dal.daointerface.CeiceiItemDAO;
import com.ceicei.project.dal.daointerface.CeiceiItemsPriceLogDAO;
import com.ceicei.project.dal.dataobject.CeiceiItemDO;
import com.ceicei.project.dal.dataobject.CeiceiItemsPriceLogDO;
import com.ceicei.util.CeiceiConstants;
import com.ceicei.util.ExtractCaptcha;
import com.ceicei.util.GetWebContent;
import com.zhz.project.common.util.alibaba.StringUtil;

public class JingDongMain implements Runnable {
    private static Log             logger    = LogFactory.getLog(JingDongMain.class);

    //用于构建链接
    public static String           url_begin = "http://price.360buyimg.com/gp";
    public static String           url_end   = ",3.png";
    private CeiceiItemDAO          ceiceiItemDAO;
    private CeiceiItemsPriceLogDAO ceiceiItemsPriceLogDAO;

    public List<String>            logList   = new ArrayList<String>();
    //线程数量
    private int                    threadCount;
    //线程编号
    private int                    threadNo;

    public JingDongMain(int threadCount, int threadNo) {
        this.threadCount = threadCount;
        this.threadNo = threadNo;
    }

    public static void go(String arg) {

        //接受唯一参数：线程个数
        if (StringUtil.isNumeric(arg)) {
            logger.info("=========================JingDongMain-BEGIN=========================");

            int threadCount = Integer.parseInt(arg);
            logger.info("线程数" + threadCount);

            //创建threadCount个线程同时处理
            for (int index = 0; index < threadCount; index++) {
                Thread t = new Thread(new JingDongMain(threadCount, index));
                t.start();
            }
        }
    }

    public void init() {

        //加载spring容器，
        ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            new String[] { "ibatis-spring.xml" });

        ceiceiItemDAO = (CeiceiItemDAO) appContext.getBean("ceiceiItemDAO");
        ceiceiItemsPriceLogDAO = (CeiceiItemsPriceLogDAO) appContext
            .getBean("ceiceiItemsPriceLogDAO");

    }

    public void run() {
        init();

        //线程开始时间
        Date begin = new Date();

        //把京东的数据提取出来
        List<CeiceiItemDO> ceiceiItemDOList = ceiceiItemDAO.getBySource("jingdong");

        //记录该线程成功处理的个数
        int successCount = 0;

        if (ceiceiItemDOList != null && ceiceiItemDOList.size() > 0) {

            for (CeiceiItemDO ceiceiItemDO : ceiceiItemDOList) {

                //本线程只处理特定的商品
                if (ceiceiItemDO.getItemid() % threadCount == threadNo) {
                    //处理单个商品
                    processSingle(ceiceiItemDO.getItemid(), ceiceiItemDO.getUrlId(), ceiceiItemDO
                        .getSource(), false);

                    successCount++;
                }
            }
        }
        synchronized (this) {
            //输出处理开始和结束时间
            logger.info("==========JingDongMain-ThreadNo:" + this.threadNo + "==========");
            logger.info(begin);
            for (String str : logList) {
                logger.info(str);
            }
            logger.info(new Date());
            logger.info("该线程成功处理商品个数：" + successCount);
            logger.info("==========JingDongMain-ThreadNo:" + this.threadNo + "==========");
        }
    }

    /**
     * 
     * 处理单个商品
     *
     * @param itemid    ceicei_items表的主键
     * @param urlId     京东的内部id
     * @param source    京东
     */
    public void processSingle(int itemid, long urlId, String source, boolean single) {
        //获取商品的ID，构造商品价格图片的链接
        Float price = parse(this.threadNo, urlId, single);
        if (price != null) {
            savePrice(itemid, price, source, single);
        }
    }

    /**
     * 根据商品ID获取商品价格图片，并进行处理
     * @param threadNo
     * @param urlId
     * @param single 
     * @return
     */
    public Float parse(int threadNo, long urlId, boolean single) {

        String url = JingDongMain.url_begin + urlId + JingDongMain.url_end;

        //获取价格图片，保存到本地
        String targetFilePath = GetWebContent.getCustomedBinaryContent(url, urlId + "");
        String code = ExtractCaptcha.extract(targetFilePath, logList, single);

        //处理完删除图片
        deleteFile(targetFilePath, single);

        return ExtractCaptcha.getNumeric(threadNo, code, urlId + "", logList, single);
    }

    /**
     * 
     * 保存获取的最新价格
     *
     * @param itemid
     * @param price
     * @param source
     * @param single 
     * @return
     */
    private void savePrice(int itemid, Float price, String source, boolean single) {

        //查看最后一次的价格
        CeiceiItemsPriceLogDO old = ceiceiItemsPriceLogDAO.getLastPriceByItemid(itemid);

        //不为空且价格没有变动，不需要处理
        if (old != null && price == old.getPrice()) {
            if (single) {
                logger.info("Thread:" + threadNo + "\titemid:" + itemid + "\tprice not change:"
                            + price);
            } else {
                logList.add("Thread:" + threadNo + "\titemid:" + itemid + "\tprice not change:"
                            + price);
            }
            return;
        }
        if (single) {
            logger.info("Thread:" + threadNo + "\tinsert itemid:" + itemid + "\tprice:" + price
                        + "\t");
        } else {
            logList.add("Thread:" + threadNo + "\tinsert itemid:" + itemid + "\tprice:" + price
                        + "\t");
        }
        //其他情況下需要插入新的价格 
        CeiceiItemsPriceLogDO ceiceiItemsPriceLogDO = new CeiceiItemsPriceLogDO();

        ceiceiItemsPriceLogDO.setItemid(itemid);
        ceiceiItemsPriceLogDO.setPrice(price);
        ceiceiItemsPriceLogDO.setPriceType(CeiceiConstants.price_type_normal);
        ceiceiItemsPriceLogDO.setSource(source);
        ceiceiItemsPriceLogDO.setCreatetime(new Date());
        //收藏商品时，不需要发送
        if (single) {
            ceiceiItemsPriceLogDO.setSmsed(CeiceiConstants.SMSED_NO_NEED);
            ceiceiItemsPriceLogDO.setMailed(CeiceiConstants.MAILED_NO_NEED);
        }
        ceiceiItemsPriceLogDAO.insert(ceiceiItemsPriceLogDO);

    }

    /**  
     * 删除单个文件  
     * @param   sPath    被删除文件的文件名  
     * @param single 
     * @return 单个文件删除成功返回true，否则返回false  
     */
    public boolean deleteFile(String sPath, boolean single) {

        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除   
        if (file.isFile() && file.exists()) {
            file.delete();
            if (single) {
                logger.info("delete file:" + sPath);
            } else {
                logList.add("delete file:" + sPath);
            }
            flag = true;
        }
        return flag;
    }
}
